package com.zzzzzz.sys.user.client;

import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Repository;
import com.zzzzzz.oms.GCS;
import com.zzzzzz.plugins.jdbctemplate.BaseDao;
import com.zzzzzz.plugins.jdbctemplate.Finder;
import com.zzzzzz.plugins.shiro.ShiroUtils;
import com.zzzzzz.sys.client.Client;

@Repository
public class UserClientDao {
	
	@Resource
	private BaseDao baseDao;
	
	private final static String sql_add = "insert into t_user_client(userId, clientId) values(:userId, :clientId)";
	private final static String sql_delByUserId = "delete from t_user_client where userId = :userId";
	private final static String sql_delByClientId = "delete from t_user_client where clientId = :clientId";
	
	private final static String sql_findClientIdListByUserId = "select clientId from t_user_client where userId=:userId";
	private final static String sql_findClientListByUserId = "select r.* from t_user_client ur inner join t_client r on ur.clientId = r.id where ur.userId = :userId and r.st = 0 order by r.updDt";
	
	public int add(UserClient userClient){
		return baseDao.update(sql_add, userClient);
	}
	
	public int delByUserId(Long userId){
		Finder finder = new Finder(sql_delByUserId).setParam("userId", userId);
		return baseDao.update(finder);
	}
	
	public int delByClientId(Long clientId){
		Finder finder = new Finder(sql_delByClientId).setParam("clientId", clientId);
		return baseDao.update(finder);
	}
	
	public List<Long> findClientIdListByUserId(Long userId){
		Finder finder = new Finder(sql_findClientIdListByUserId).setParam("userId", userId);
		List<Long> clientList = baseDao.findListSingleColumn(finder, Long.class);
		return clientList;
	}
	
	public List<Client> findClientListByUserId(Long userId){
		Finder finder = new Finder(sql_findClientListByUserId).setParam("userId", userId);
		List<Client> clientList = baseDao.findList(finder, Client.class);
		return clientList;
	}
	
	/*
	 * 场景：用户管理界面的角色管理。
	 * 根据所选择的用户，查看此用户所在平台的所有角色，和用户所对应的所有角色(checked)
	 * 如果是超级管理员，则可查看到所有平台的所有角色
	 */
	public List<Map<String, Object>> findClientListByUserIdForSelect(Long userId){
		Finder finder = new Finder("select r.*, ur.userId")
		.append("from");
		if(ShiroUtils.ifSuperAdministrator()){
			finder.append("t_client r");
		}else{
			finder.append("(select * from t_client where platformId = :platformId)r").setParam(GCS.COL_PLATFORM_ID, ShiroUtils.findPlatformId());
		}
		finder.append("left join t_user_client ur on ur.clientId = r.id and ur.userId = :userId")
		.append("where r.st = 0 order by r.updDt")
		.setParam("userId", userId);
		
		List<Map<String, Object>> list = baseDao.findList(finder);
		return list;
	}
}
